package com.catemanagement.plugin;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import com.catemanagement.model.Bill;
import com.catemanagement.model.BillMenu;
import com.catemanagement.model.Menu;
import com.catemanagement.utils.PrintUtil;

public class PrintPlugin extends CordovaPlugin {
    private PrintWriter printWriter;

    private Socket printSocket;
    public void shutdownPrinter() throws IOException {
        printWriter.close();
        printSocket.close();
    }

    public void connectPrinter() throws IOException {
        printSocket = new Socket();
        String ip = "172.16.113.218";
        int port = 9100;
        printSocket.connect(new InetSocketAddress(ip, port), 3000);
        OutputStreamWriter os = new OutputStreamWriter(printSocket.getOutputStream(), "GBK");
        printWriter = new PrintWriter(os, true);

    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        try {
            JSONObject jsonObject = args.getJSONObject(0);
            Double totalPrice = getDouble(jsonObject, "totalPrice");
            String tableName = getString(jsonObject, "tableName");
            Bill bill = new Bill();
            bill.setTableName(tableName);
            bill.setSendTime(new Date());
            bill.setTotalPrice(totalPrice.floatValue());
            JSONArray menuList = jsonObject.getJSONArray("menuList");
            for (int i = 0; i < menuList.length(); i++) {
                JSONObject menuJsonObject = menuList.getJSONObject(i);
                String name = getString(menuJsonObject, "name");
                String unit = getString(menuJsonObject, "unit");
                Double count = getDouble(menuJsonObject, "count");
                Double unitPrice = getDouble(menuJsonObject, "unitPrice");

                Menu menu = new Menu();
                menu.setCategoryId(1L);
                menu.setName(name);
                menu.setUnit(unit);
                menu.setUnitPrice(unitPrice.floatValue());
                BillMenu billMenu = new BillMenu(menu);
                billMenu.setCount(count.floatValue());
                bill.addBillMenu(billMenu);
            }
            connectPrinter();
            PrintUtil.print(printWriter, bill);
            shutdownPrinter();
            JSONObject result = new JSONObject();
            result.put("success", true);
            result.put("msg", "打印成功");
            callbackContext.success(result);
            return true;
        } catch (Exception e) {
            Log.e("print", e.getMessage(), e);
            JSONObject result = new JSONObject();
            result.put("success", false);
            result.put("msg", "打印失败:" + e.getClass());
            callbackContext.error(result);
            return false;
        }

    }

    private Double getDouble(JSONObject jsonObject, String property) {
        try {
            return jsonObject.getDouble(property);
        } catch (JSONException e) {
            Log.e("json", e.getMessage(), e);
            return null;
        }
    }

    private String getString(JSONObject jsonObject, String property) {
        try {
            return jsonObject.getString(property);
        } catch (JSONException e) {
            Log.e("json", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public boolean execute(String action, String rawArgs, CallbackContext callbackContext) throws JSONException {
        Log.e("printPlugin", rawArgs);
        return super.execute(action, rawArgs, callbackContext);
    }

    /**
     * 获取软件版本号
     * 
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        // TODO Auto-generated method stub
        int versionCode = 0;

        // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
        try {
            versionCode = context.getPackageManager().getPackageInfo("com.catemanagement", 0).versionCode;
        } catch (NameNotFoundException e) {
        }
        return versionCode;
    }

}
